<!DOCTYPE html>
<html  lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="renderer" content="webkit">
    <th:block th:include="include :: header('语音播报')" />
    <!-- 避免IE使用兼容模式 -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
</head>
<body class="gray-bg">
<div class="wrapper wrapper-content animated fadeIn">
    <div class="row">
        <div class="col-sm-12">
            <div class="ibox float-e-margins">
                <div class="ibox-title">
                    <input id="playedIds" type="hidden" th:value="${playedIds}">
                    <h2 style="display:inline-block;margin-right:10px;">播报内容</h2>
                    <a class="btn btn-primary btn-rounded" id="listen" href="#" onclick="changeStatus()">开始</a>
                </div>
                <div id="contentBox" class="ibox-content"></div>
            </div>
        </div>
    </div>

<th:block th:include="include :: footer" />
<script th:inline="javascript">
    var ctx = [[@{/}]];
    var prefix = ctx + "back/shopOrderAnnounce";
    const synth = window.speechSynthesis;
    const inputForm = document.querySelector("form");
    const inputTxt = document.querySelector(".txt");
    const voiceSelect = document.querySelector("select");

    let lastId=0;
    let voices = [];
    let timer =null;
    let player =null;
    let prePlayList =[];
    let playedIds = $('#playedIds').val();
    let playedList =[];
    if(playedIds != ''){
        playedList = playedIds.split(",");
        lastId = playedList[0];
    }
    let isBegin = false;
    let isFetchMsg = true;

    $.ajaxSetup({
        complete: function(XMLHttpRequest, textStatus) {
            if (textStatus == 'timeout') {
                $.modal.enable();
                $.modal.closeLoading();
            } else if (textStatus == "parsererror" || textStatus == "error") {
                $.modal.enable();
                $.modal.closeLoading();
            }
        }
    });


    function changeStatus() {
        if (synth.speaking) {
            // console.error("speechSynthesis.speaking");
            return;
        }
        if(!isBegin){
            isBegin=true;
            $('#listen').addClass("btn-warning").removeClass("btn-primary").html("暂停");
            timer=self.setInterval("fetchVoicePlayList()",1000);
            player=self.setInterval("doPlay()",1000);
        }else{
            isBegin=false;
            isFetchMsg=true;
            $('#listen').addClass("btn-primary").removeClass("btn-warning").html("开始");
            clearInterval(timer);
            clearInterval(player);
        }
    }

    function populateVoiceList() {
        voices = synth.getVoices().sort(function (a, b) {
            const aname = a.name.toUpperCase();
            const bname = b.name.toUpperCase();

            if (aname < bname) {
                return -1;
            } else if (aname == bname) {
                return 0;
            } else {
                return +1;
            }
        });
    }

    if (speechSynthesis.onvoiceschanged !== undefined) {
        speechSynthesis.onvoiceschanged = populateVoiceList;
    }

    function doPlay() {
        if (synth.speaking || 0 == prePlayList.length) {
            // console.error("speechSynthesis.speaking");
            return;
        }
        speak(prePlayList.shift());
    }

    function speak(annId) {
        if (synth.speaking) {
            // console.error("speechSynthesis.speaking");
            return;
        }
        if(annId<=0){
            return;
        }
        let content = $('.annContent[data-id="'+annId+'"]').text();
        if (content !== "") {
            $('.alert-link[data-id="'+annId+'"]').html("<i class=\"fa fa-pause\"></i>");
            $('.annContent[data-id="'+annId+'"]').parent().addClass("alert-warning").removeClass("alert-danger");
            const utterThis = new SpeechSynthesisUtterance(content);

            utterThis.onend = function (event) {
                $('.alert-link[data-id="'+annId+'"]').html("<i class=\"fa fa-play-circle\"></i>");
                $('.annContent[data-id="'+annId+'"]').parent().addClass("alert-success").removeClass("alert-warning");
                lastId=annId;
                playedList.push(annId);
                if(playedList.length>5){
                    var shiftId = playedList.shift();
                    $('.annContent[data-id="'+shiftId+'"]').parent().remove();
                }
                if(prePlayList.length == 0){
                    isFetchMsg = true;
                }
            };

            utterThis.onerror = function (event) {
                console.error("SpeechSynthesisUtterance.onerror");
            };

            for (let i = 0; i < voices.length; i++) {
                if (voices[i].default) {
                    utterThis.voice = voices[i];
                    break;
                }
            }
            utterThis.pitch = 2;
            utterThis.rate = 1;
            synth.speak(utterThis);
        }
    }

    function fetchVoicePlayList() {
        if(!isFetchMsg){return;}
        isFetchMsg = false;
        $.ajax({
            type: 'get',
            url: prefix + "/getLastestList/"+lastId,
            dataType: 'json',
            async: false,
            success: function (result){
                if(null == result.data || 0 == result.data.length){
                    isFetchMsg = true;
                    return;
                }
                //队列保存最新5条数据
                for(let i=0;i<result.data.length;i++){
                    let isExist = false;
                    let one = result.data[i];
                    for (let j=0;j<playedList.length;j++) {
                        if (one.id == playedList[j]) {
                            isExist = true;
                            break;
                        }
                    }
                    if(isExist){
                        continue;
                    }
                    let appendStr = "<div class=\"alert alert-danger alert-dismissable\">" +
                        "<button aria-hidden=\"true\" data-dismiss=\"alert\" class=\"close\" type=\"button\">×</button>" +
                        "<span style=\"font-size:40px;\" class=\"annContent mr10\" data-id=\""+one.id+"\">"+one.annTitle+"</span>" +
                        "<span style=\"font-size:40px;\" class=\"mr10\">"+" 支付时间："+one.createTime+"</span>"+
                        "<a class=\"alert-link\" href=\"#\" data-id=\""+one.id+"\" onclick=\"speak("+one.id+")\"><i class=\"fa fa-play\"></i></a>" +
                        "</div>";
                    $('#contentBox').prepend(appendStr);
                    prePlayList.push(one.id);
                }
            },
            error: function (request) {
                //
            }

        });
    }
</script>
</body>
</html>